/**
 * 初始化数据库脚本
 * 为MongoDB创建索引并添加测试数据
 */

const mongoose = require('mongoose');
const bcryptjs = require('bcryptjs');

// 数据库连接信息
const uri = 'mongodb://localhost:27017/health_app';

// 创建MongoDB ObjectId
const ObjectId = mongoose.Types.ObjectId;
const createObjectId = () => new ObjectId();

// 生成测试数据的辅助函数
function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function getRandomElement(array) {
  return array[Math.floor(Math.random() * array.length)];
}

function getRandomDate(start, end) {
  return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()));
}

// 生成Unsplash随机图片URL
function getUnsplashImage(width, height, category) {
  const categories = category ? `${category}` : '';
  return `https://source.unsplash.com/random/${width}x${height}/?${categories}`;
}

// 生成用户数据
async function generateUsers(count) {
  const genders = [0, 1, 2]; // 0-未知，1-男，2-女
  const activityLevels = [1, 2, 3, 4, 5]; // 从久坐到极高活动量
  const goals = ['减脂', '增肌', '健康饮食'];
  
  const users = [];
  
  for (let i = 0; i < count; i++) {
    const gender = getRandomElement(genders);
    const weight = getRandomInt(45, 100);
    const height = getRandomInt(150, 190);
    const age = getRandomInt(18, 60);
    const activityLevel = getRandomElement(activityLevels);
    const goal = getRandomElement(goals);
    
    // 计算每日卡路里目标 (基于基础代谢率BMR和活动水平)
    let bmr;
    if (gender === 1) { // 男性
      bmr = 10 * weight + 6.25 * height - 5 * age + 5;
    } else { // 女性或未知
      bmr = 10 * weight + 6.25 * height - 5 * age - 161;
    }
    
    // 根据活动水平调整
    const activityMultipliers = [1.2, 1.375, 1.55, 1.725, 1.9];
    const dailyCalorieGoal = Math.round(bmr * activityMultipliers[activityLevel - 1]);
    
    users.push({
      _id: createObjectId(),
      openid: `openid_${i}`,
      unionid: `unionid_${i}`,
      nickname: `用户${i + 1}`,
      avatar: getUnsplashImage(200, 200, 'person'),
      gender,
      height,
      weight,
      age,
      activityLevel,
      goal,
      dailyCalorieGoal,
      createdAt: getRandomDate(new Date(2022, 0, 1), new Date()),
      updatedAt: new Date(),
      lastLoginAt: getRandomDate(new Date(2023, 0, 1), new Date()),
      isActive: Math.random() > 0.1 // 90%的用户是活跃的
    });
  }
  
  return users;
}

// 生成管理员数据
async function generateAdminUsers() {
  const saltRounds = 10;
  const adminPassword = await bcryptjs.hash('admin123', saltRounds);
  
  return [
    {
      _id: createObjectId(),
      username: 'admin',
      password: adminPassword,
      name: '系统管理员',
      avatar: getUnsplashImage(200, 200, 'professional'),
      email: 'admin@example.com',
      phone: '13800138000',
      role: 'admin',
      permissions: ['all'],
      createdAt: new Date(),
      updatedAt: new Date(),
      lastLoginAt: new Date(),
      isActive: true
    }
  ];
}

// 生成食物分类数据
function generateFoodCategories() {
  const categories = [
    { name: '谷物类', icon: 'grain', description: '包括各种米面、杂粮等' },
    { name: '蔬菜类', icon: 'vegetable', description: '各类绿叶、根茎、瓜果蔬菜' },
    { name: '水果类', icon: 'fruit', description: '各类新鲜水果' },
    { name: '肉类', icon: 'meat', description: '猪牛羊等红肉和家禽类' },
    { name: '海鲜类', icon: 'seafood', description: '各类鱼虾蟹贝等海产品' },
    { name: '蛋奶类', icon: 'dairy', description: '奶制品、蛋类食品' },
    { name: '豆制品', icon: 'tofu', description: '各类豆腐、豆浆等豆制品' },
    { name: '坚果类', icon: 'nuts', description: '各类干果、坚果' },
    { name: '零食饮料', icon: 'snack', description: '休闲零食和各类饮料' },
    { name: '调味品', icon: 'condiment', description: '各类调味料和香料' }
  ];
  
  return categories.map((category, index) => ({
    _id: createObjectId(),
    name: category.name,
    icon: category.icon,
    description: category.description,
    order: index + 1,
    isActive: true
  }));
}

// 生成食物数据
function generateFoods(foodCategories) {
  const foods = [];
  
  // 谷物类
  const grains = [
    { name: '白米饭', unit: '克', calories: 116 },
    { name: '糙米饭', unit: '克', calories: 111 },
    { name: '燕麦片', unit: '克', calories: 389 },
    { name: '全麦面包', unit: '克', calories: 265 },
    { name: '意大利面', unit: '克', calories: 158 }
  ];
  
  // 蔬菜类
  const vegetables = [
    { name: '西兰花', unit: '克', calories: 34 },
    { name: '胡萝卜', unit: '克', calories: 41 },
    { name: '西红柿', unit: '克', calories: 18 },
    { name: '菠菜', unit: '克', calories: 23 },
    { name: '白菜', unit: '克', calories: 12 }
  ];
  
  // 水果类
  const fruits = [
    { name: '苹果', unit: '克', calories: 52 },
    { name: '香蕉', unit: '克', calories: 89 },
    { name: '橙子', unit: '克', calories: 47 },
    { name: '草莓', unit: '克', calories: 32 },
    { name: '蓝莓', unit: '克', calories: 57 }
  ];
  
  // 肉类
  const meats = [
    { name: '鸡胸肉', unit: '克', calories: 165 },
    { name: '牛肉', unit: '克', calories: 250 },
    { name: '猪肉', unit: '克', calories: 242 },
    { name: '羊肉', unit: '克', calories: 294 },
    { name: '火鸡肉', unit: '克', calories: 189 }
  ];
  
  // 海鲜类
  const seafoods = [
    { name: '三文鱼', unit: '克', calories: 208 },
    { name: '虾', unit: '克', calories: 99 },
    { name: '金枪鱼', unit: '克', calories: 184 },
    { name: '扇贝', unit: '克', calories: 111 },
    { name: '鳕鱼', unit: '克', calories: 82 }
  ];
  
  // 蛋奶类
  const dairy = [
    { name: '牛奶', unit: '毫升', calories: 42 },
    { name: '酸奶', unit: '克', calories: 59 },
    { name: '鸡蛋', unit: '个', calories: 155 },
    { name: '奶酪', unit: '克', calories: 402 },
    { name: '酪乳', unit: '毫升', calories: 40 }
  ];
  
  // 把所有食物合并
  const allFoods = [
    ...grains.map(food => ({ ...food, category: foodCategories.find(c => c.name === '谷物类') })),
    ...vegetables.map(food => ({ ...food, category: foodCategories.find(c => c.name === '蔬菜类') })),
    ...fruits.map(food => ({ ...food, category: foodCategories.find(c => c.name === '水果类') })),
    ...meats.map(food => ({ ...food, category: foodCategories.find(c => c.name === '肉类') })),
    ...seafoods.map(food => ({ ...food, category: foodCategories.find(c => c.name === '海鲜类') })),
    ...dairy.map(food => ({ ...food, category: foodCategories.find(c => c.name === '蛋奶类') }))
  ];
  
  // 为每个食物生成完整信息
  allFoods.forEach(food => {
    const protein = food.category.name === '肉类' || food.category.name === '海鲜类' ? 
      getRandomInt(15, 25) : getRandomInt(1, 10);
      
    const fat = food.category.name === '肉类' || food.category.name === '坚果类' ?
      getRandomInt(10, 20) : getRandomInt(0, 5);
      
    const carbs = food.category.name === '谷物类' || food.category.name === '水果类' ?
      getRandomInt(20, 40) : getRandomInt(0, 10);
    
    foods.push({
      _id: createObjectId(),
      name: food.name,
      category: {
        _id: food.category._id,
        name: food.category.name
      },
      image: getUnsplashImage(400, 300, `${food.name},food`),
      unit: food.unit,
      calories: food.calories,
      nutrition: {
        protein: protein,
        fat: fat,
        carbohydrate: carbs,
        fiber: getRandomInt(0, 5),
        sugar: getRandomInt(0, 10),
        sodium: getRandomInt(0, 500),
        cholesterol: getRandomInt(0, 100),
        vitamins: {
          A: getRandomInt(0, 1000),
          C: getRandomInt(0, 100),
          D: getRandomInt(0, 20),
          E: getRandomInt(0, 15),
          K: getRandomInt(0, 100),
          B1: getRandomInt(0, 2),
          B2: getRandomInt(0, 2),
          B6: getRandomInt(0, 2),
          B12: getRandomInt(0, 10)
        },
        minerals: {
          calcium: getRandomInt(0, 200),
          iron: getRandomInt(0, 10),
          magnesium: getRandomInt(0, 100),
          potassium: getRandomInt(0, 400),
          zinc: getRandomInt(0, 5)
        }
      },
      isVerified: true,
      source: '中国食物成分表',
      createdAt: new Date(),
      updatedAt: new Date()
    });
  });
  
  return foods;
}

// 生成食谱分类数据
function generateRecipeCategories() {
  const categories = [
    { name: '早餐', icon: 'breakfast', description: '营养健康的早餐食谱' },
    { name: '午餐', icon: 'lunch', description: '美味可口的午餐食谱' },
    { name: '晚餐', icon: 'dinner', description: '丰盛营养的晚餐食谱' },
    { name: '减脂餐', icon: 'diet', description: '低热量、高蛋白的减脂餐' },
    { name: '增肌餐', icon: 'muscle', description: '高蛋白、高能量的增肌餐' },
    { name: '素食', icon: 'vegetarian', description: '各式素食料理' },
    { name: '小吃甜点', icon: 'dessert', description: '健康美味的小吃和甜点' },
    { name: '汤品', icon: 'soup', description: '滋补养生的各类汤品' },
    { name: '儿童餐', icon: 'kids', description: '适合儿童的营养餐' },
    { name: '特殊功能', icon: 'special', description: '针对特殊功能的营养食谱' }
  ];
  
  return categories.map((category, index) => ({
    _id: createObjectId(),
    name: category.name,
    icon: category.icon,
    description: category.description,
    order: index + 1,
    isActive: true
  }));
}

// 生成食谱数据
function generateRecipes(recipeCategories, foods, adminUser) {
  const recipes = [];
  
  // 定义一些示例食谱
  const recipeTemplates = [
    {
      title: '燕麦水果早餐碗',
      description: '富含膳食纤维和维生素的健康早餐',
      category: '早餐',
      difficulty: 1,
      ingredients: ['燕麦片', '牛奶', '香蕉', '蓝莓'],
      tags: ['健康', '高纤维', '快手早餐']
    },
    {
      title: '鸡胸肉蔬菜沙拉',
      description: '低脂高蛋白的健康减脂餐',
      category: '减脂餐',
      difficulty: 2,
      ingredients: ['鸡胸肉', '西兰花', '西红柿', '胡萝卜'],
      tags: ['减脂', '高蛋白', '低碳水']
    },
    {
      title: '三文鱼牛油果饭碗',
      description: '高蛋白高健康脂肪的增肌餐',
      category: '增肌餐',
      difficulty: 3,
      ingredients: ['三文鱼', '白米饭', '西兰花'],
      tags: ['增肌', '高蛋白', '健康脂肪']
    },
    {
      title: '意大利面沙拉',
      description: '清爽可口的午餐选择',
      category: '午餐',
      difficulty: 2,
      ingredients: ['意大利面', '西红柿', '黄瓜', '橄榄油'],
      tags: ['地中海', '轻食', '简单']
    },
    {
      title: '牛肉蔬菜汤',
      description: '营养丰富的晚餐汤品',
      category: '晚餐',
      difficulty: 3,
      ingredients: ['牛肉', '胡萝卜', '洋葱', '西红柿'],
      tags: ['营养', '低脂', '保暖']
    },
    {
      title: '烤三文鱼配蔬菜',
      description: '简单美味的高蛋白晚餐',
      category: '晚餐',
      difficulty: 3,
      ingredients: ['三文鱼', '西兰花', '胡萝卜', '橄榄油'],
      tags: ['欧式', '高蛋白', '健康脂肪']
    },
    {
      title: '水果酸奶杯',
      description: '健康美味的小食',
      category: '小吃甜点',
      difficulty: 1,
      ingredients: ['酸奶', '草莓', '蓝莓', '香蕉'],
      tags: ['低糖', '营养', '快手']
    },
    {
      title: '蔬菜沙拉',
      description: '清爽可口的素食沙拉',
      category: '素食',
      difficulty: 1,
      ingredients: ['西红柿', '黄瓜', '胡萝卜', '橄榄油'],
      tags: ['素食', '低卡', '简单']
    },
    {
      title: '蔬菜浓汤',
      description: '营养丰富的素食汤品',
      category: '汤品',
      difficulty: 2,
      ingredients: ['西红柿', '胡萝卜', '洋葱', '土豆'],
      tags: ['素食', '营养', '温暖']
    },
    {
      title: '水果奶昔',
      description: '营养丰富的儿童早餐',
      category: '儿童餐',
      difficulty: 1,
      ingredients: ['牛奶', '香蕉', '草莓', '蓝莓'],
      tags: ['营养', '快手', '儿童喜爱']
    }
  ];
  
  // 为每个模板食谱创建实际数据
  recipeTemplates.forEach(template => {
    const category = recipeCategories.find(c => c.name === template.category);
    const recipeIngredients = template.ingredients.map(ingName => {
      const food = foods.find(f => f.name === ingName);
      if (!food) return null;
      return {
        food: {
          _id: food._id,
          name: food.name
        },
        amount: getRandomInt(50, 200),
        unit: food.unit
      };
    }).filter(ing => ing !== null);
    
    const steps = [];
    for (let i = 1; i <= getRandomInt(3, 6); i++) {
      steps.push({
        stepNumber: i,
        description: `步骤${i}：这是食谱${template.title}的第${i}步骤`,
        image: getUnsplashImage(400, 300, `cooking,step,${template.title}`)
      });
    }
    
    // 计算营养成分
    const nutrition = {
      calories: getRandomInt(200, 600),
      protein: getRandomInt(5, 30),
      fat: getRandomInt(5, 20),
      carbohydrate: getRandomInt(10, 60)
    };
    
    recipes.push({
      _id: createObjectId(),
      title: template.title,
      description: template.description,
      coverImage: getUnsplashImage(600, 400, `${template.title},food`),
      category: {
        _id: category._id,
        name: category.name
      },
      difficulty: template.difficulty,
      prepTime: getRandomInt(5, 20),
      cookTime: getRandomInt(10, 60),
      servings: getRandomInt(1, 4),
      ingredients: recipeIngredients,
      steps: steps,
      nutrition: nutrition,
      tags: template.tags,
      author: {
        _id: adminUser._id,
        name: adminUser.name
      },
      isVerified: true,
      viewCount: getRandomInt(10, 1000),
      favoriteCount: getRandomInt(5, 500),
      rating: (getRandomInt(30, 50) / 10),
      reviewCount: getRandomInt(5, 100),
      createdAt: getRandomDate(new Date(2023, 0, 1), new Date()),
      updatedAt: new Date()
    });
  });
  
  return recipes;
}

// 生成系统配置数据
function generateSystemConfigs(adminUser) {
  return [
    {
      _id: createObjectId(),
      key: 'app_name',
      value: '健康饮食营养师',
      category: 'system',
      description: '应用名称',
      isSystem: true,
      isActive: true,
      createdAt: new Date(),
      updatedAt: new Date(),
      createdBy: adminUser._id,
      updatedBy: adminUser._id
    },
    {
      _id: createObjectId(),
      key: 'app_logo',
      value: getUnsplashImage(512, 512, 'healthy,food,logo'),
      category: 'system',
      description: '应用Logo',
      isSystem: true,
      isActive: true,
      createdAt: new Date(),
      updatedAt: new Date(),
      createdBy: adminUser._id,
      updatedBy: adminUser._id
    },
    {
      _id: createObjectId(),
      key: 'app_version',
      value: '1.0.0',
      category: 'system',
      description: '应用版本号',
      isSystem: true,
      isActive: true,
      createdAt: new Date(),
      updatedAt: new Date(),
      createdBy: adminUser._id,
      updatedBy: adminUser._id
    },
    {
      _id: createObjectId(),
      key: 'maintenance_mode',
      value: false,
      category: 'system',
      description: '维护模式',
      isSystem: true,
      isActive: true,
      createdAt: new Date(),
      updatedAt: new Date(),
      createdBy: adminUser._id,
      updatedBy: adminUser._id
    },
    {
      _id: createObjectId(),
      key: 'default_user_avatar',
      value: getUnsplashImage(200, 200, 'avatar,default'),
      category: 'user',
      description: '默认用户头像',
      isSystem: true,
      isActive: true,
      createdAt: new Date(),
      updatedAt: new Date(),
      createdBy: adminUser._id,
      updatedBy: adminUser._id
    },
    {
      _id: createObjectId(),
      key: 'default_food_image',
      value: getUnsplashImage(400, 300, 'food,plate'),
      category: 'food',
      description: '默认食物图片',
      isSystem: true,
      isActive: true,
      createdAt: new Date(),
      updatedAt: new Date(),
      createdBy: adminUser._id,
      updatedBy: adminUser._id
    },
    {
      _id: createObjectId(),
      key: 'default_recipe_image',
      value: getUnsplashImage(600, 400, 'recipe,cooking'),
      category: 'recipe',
      description: '默认食谱图片',
      isSystem: true,
      isActive: true,
      createdAt: new Date(),
      updatedAt: new Date(),
      createdBy: adminUser._id,
      updatedBy: adminUser._id
    },
    {
      _id: createObjectId(),
      key: 'search_history_limit',
      value: 20,
      category: 'user',
      description: '用户搜索历史记录上限',
      isSystem: true,
      isActive: true,
      createdAt: new Date(),
      updatedAt: new Date(),
      createdBy: adminUser._id,
      updatedBy: adminUser._id
    },
    {
      _id: createObjectId(),
      key: 'diet_record_image_limit',
      value: 5,
      category: 'diet_record',
      description: '每条饮食记录图片上限',
      isSystem: true,
      isActive: true,
      createdAt: new Date(),
      updatedAt: new Date(),
      createdBy: adminUser._id,
      updatedBy: adminUser._id
    },
    {
      _id: createObjectId(),
      key: 'recipe_step_image_limit',
      value: 1,
      category: 'recipe',
      description: '每个食谱步骤图片上限',
      isSystem: true,
      isActive: true,
      createdAt: new Date(),
      updatedAt: new Date(),
      createdBy: adminUser._id,
      updatedBy: adminUser._id
    }
  ];
}

// 生成用户活动日志
function generateUserActivityLogs(users, adminUser) {
  const logs = [];
  
  // 管理员活动日志
  const adminActions = [
    { actionType: 'login', module: 'system', description: '管理员登录系统' },
    { actionType: 'create', module: 'food', description: '创建新食物数据' },
    { actionType: 'update', module: 'recipe', description: '更新食谱信息' },
    { actionType: 'verify', module: 'food', description: '审核食物数据' },
    { actionType: 'delete', module: 'user', description: '删除不活跃用户' }
  ];
  
  // 为管理员生成日志
  for (let i = 0; i < 10; i++) {
    const action = getRandomElement(adminActions);
    logs.push({
      _id: createObjectId(),
      userId: adminUser._id,
      userType: 'admin',
      actionType: action.actionType,
      module: action.module,
      details: {
        description: action.description
      },
      ipAddress: '127.0.0.1',
      userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
      deviceInfo: {
        platform: 'web',
        model: 'Chrome',
        system: 'Windows'
      },
      status: 'success',
      createdAt: getRandomDate(new Date(2023, 0, 1), new Date())
    });
  }
  
  // 用户活动日志
  const userActions = [
    { actionType: 'login', module: 'user', description: '用户登录' },
    { actionType: 'add', module: 'diet_record', description: '添加饮食记录' },
    { actionType: 'favorite', module: 'recipe', description: '收藏食谱' },
    { actionType: 'search', module: 'food', description: '搜索食物' },
    { actionType: 'view', module: 'recipe', description: '查看食谱详情' }
  ];
  
  // 为每个用户生成活动日志
  users.forEach(user => {
    for (let i = 0; i < 5; i++) {
      const action = getRandomElement(userActions);
      logs.push({
        _id: createObjectId(),
        userId: user._id,
        userType: 'user',
        actionType: action.actionType,
        module: action.module,
        details: {
          description: `${user.nickname}${action.description}`
        },
        ipAddress: `192.168.1.${getRandomInt(1, 255)}`,
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15',
        deviceInfo: {
          platform: 'ios',
          model: 'iPhone',
          system: 'iOS 15.0'
        },
        status: 'success',
        createdAt: getRandomDate(new Date(2023, 0, 1), new Date())
      });
    }
  });
  
  return logs;
}

// 生成营养建议数据
function generateNutritionSuggestions(users) {
  const suggestions = [];
  
  const suggestionTemplates = [
    {
      type: '营养均衡',
      content: '您的饮食中蛋白质摄入不足，建议增加瘦肉、鱼类、蛋类等高蛋白食物的摄入。',
      relevantFoods: ['鸡胸肉', '三文鱼', '鸡蛋']
    },
    {
      type: '热量控制',
      content: '您近期的碳水化合物摄入较高，建议适当减少米饭、面食等淀粉类食物的摄入量，控制总热量。',
      relevantFoods: ['白米饭', '全麦面包', '意大利面']
    },
    {
      type: '营养补充',
      content: '您的膳食纤维摄入不足，建议多食用全谷物、蔬菜水果等富含膳食纤维的食物。',
      relevantFoods: ['糙米饭', '西兰花', '苹果']
    },
    {
      type: '健康提示',
      content: '您近期钠的摄入量偏高，建议减少加工食品和外卖的食用频率，减少盐的使用量。',
      relevantFoods: []
    },
    {
      type: '健康饮食',
      content: '建议每天摄入足够的水果和蔬菜，至少5种不同颜色，以获取全面的维生素和矿物质。',
      relevantFoods: ['西红柿', '菠菜', '胡萝卜', '蓝莓']
    }
  ];
  
  users.forEach(user => {
    // 每个用户2-3条建议
    const suggestionCount = getRandomInt(2, 3);
    
    for (let i = 0; i < suggestionCount; i++) {
      const template = getRandomElement(suggestionTemplates);
      suggestions.push({
        _id: createObjectId(),
        userId: user._id,
        type: template.type,
        content: template.content,
        relevantFoods: template.relevantFoods.map(foodName => ({
          foodId: createObjectId(), // 这里简化处理，实际应该关联到真实的食物ID
          reason: `富含所需${template.type === '营养均衡' ? '蛋白质' : template.type === '营养补充' ? '膳食纤维' : '营养素'}`
        })),
        createdAt: getRandomDate(new Date(2023, 0, 1), new Date()),
        isRead: Math.random() > 0.5 // 50%概率已读
      });
    }
  });
  
  return suggestions;
}

// 生成营养目标数据
function generateNutritionGoals(users) {
  const goals = [];
  
  users.forEach(user => {
    // 基于用户的基础信息计算营养目标
    const caloriesGoal = user.dailyCalorieGoal;
    
    // 计算宏量营养素比例 (蛋白质/脂肪/碳水)
    let proteinRatio, fatRatio, carbRatio;
    
    if (user.goal === '减脂') {
      // 减脂：高蛋白，中脂肪，低碳水
      proteinRatio = 0.4;
      fatRatio = 0.3;
      carbRatio = 0.3;
    } else if (user.goal === '增肌') {
      // 增肌：高蛋白，中脂肪，高碳水
      proteinRatio = 0.35;
      fatRatio = 0.25;
      carbRatio = 0.4;
    } else {
      // 健康饮食：平衡配比
      proteinRatio = 0.3;
      fatRatio = 0.3;
      carbRatio = 0.4;
    }
    
    // 计算每日宏量营养素目标（克）
    const proteinGoal = Math.round((caloriesGoal * proteinRatio) / 4); // 蛋白质4卡/克
    const fatGoal = Math.round((caloriesGoal * fatRatio) / 9); // 脂肪9卡/克
    const carbGoal = Math.round((caloriesGoal * carbRatio) / 4); // 碳水4卡/克
    
    goals.push({
      _id: createObjectId(),
      userId: user._id,
      caloriesGoal,
      nutritionGoals: {
        protein: proteinGoal,
        fat: fatGoal,
        carbohydrate: carbGoal,
        fiber: Math.round(carbGoal * 0.1), // 膳食纤维约为碳水的10%
        sugar: Math.round(carbGoal * 0.1), // 糖约为碳水的10%
        sodium: 2300, // 钠摄入限制（毫克）
      },
      macroRatio: {
        protein: proteinRatio,
        fat: fatRatio,
        carbohydrate: carbRatio
      },
      createdAt: new Date(),
      updatedAt: new Date()
    });
  });
  
  return goals;
}

// 生成食物收藏数据
function generateFoodFavorites(users, foods) {
  const favorites = [];
  
  users.forEach(user => {
    // 每个用户随机收藏3-8个食物
    const favoriteCount = getRandomInt(3, 8);
    const userFavoriteFoods = [];
    
    for (let i = 0; i < favoriteCount; i++) {
      let food;
      // 确保不重复收藏
      do {
        food = getRandomElement(foods);
      } while (userFavoriteFoods.includes(food._id.toString()));
      
      userFavoriteFoods.push(food._id.toString());
      
      favorites.push({
        _id: createObjectId(),
        userId: user._id,
        foodId: food._id,
        createdAt: getRandomDate(new Date(2023, 0, 1), new Date())
      });
    }
  });
  
  return favorites;
}

// 生成食谱收藏数据
function generateRecipeFavorites(users, recipes) {
  const favorites = [];
  
  users.forEach(user => {
    // 每个用户随机收藏2-5个食谱
    const favoriteCount = getRandomInt(2, 5);
    const userFavoriteRecipes = [];
    
    for (let i = 0; i < favoriteCount; i++) {
      let recipe;
      // 确保不重复收藏
      do {
        recipe = getRandomElement(recipes);
      } while (userFavoriteRecipes.includes(recipe._id.toString()));
      
      userFavoriteRecipes.push(recipe._id.toString());
      
      favorites.push({
        _id: createObjectId(),
        userId: user._id,
        recipeId: recipe._id,
        createdAt: getRandomDate(new Date(2023, 0, 1), new Date())
      });
    }
  });
  
  return favorites;
}

// 生成搜索历史数据
function generateSearchHistory(users) {
  const history = [];
  const foodKeywords = ['鸡胸肉', '牛奶', '蔬菜', '水果', '三文鱼', '蛋白质', '低脂', '高纤维'];
  const recipeKeywords = ['早餐', '减脂餐', '增肌餐', '沙拉', '汤', '快手', '健康', '低卡'];
  
  users.forEach(user => {
    // 每个用户5-10条搜索记录
    const historyCount = getRandomInt(5, 10);
    
    for (let i = 0; i < historyCount; i++) {
      // 随机决定是搜索食物还是食谱
      const type = Math.random() > 0.5 ? 'food' : 'recipe';
      const keywords = type === 'food' ? foodKeywords : recipeKeywords;
      
      history.push({
        _id: createObjectId(),
        userId: user._id,
        keyword: getRandomElement(keywords),
        type,
        createdAt: getRandomDate(new Date(2023, 0, 1), new Date())
      });
    }
  });
  
  return history;
}

// 生成饮食记录数据
function generateDietRecords(users, foods) {
  const records = [];
  const mealTypes = ['早餐', '午餐', '晚餐', '加餐'];
  
  users.forEach(user => {
    // 为每个用户生成最近7天的饮食记录
    for (let day = 0; day < 7; day++) {
      const date = new Date();
      date.setDate(date.getDate() - day);
      
      // 每天2-4餐
      const mealsPerDay = getRandomInt(2, 4);
      const dailyMeals = [];
      
      for (let i = 0; i < mealsPerDay; i++) {
        let mealType;
        // 确保每天的餐类型不重复
        do {
          mealType = getRandomElement(mealTypes);
        } while (dailyMeals.includes(mealType));
        
        dailyMeals.push(mealType);
        
        // 每餐2-5种食物
        const foodCount = getRandomInt(2, 5);
        const mealFoods = [];
        let totalCalories = 0;
        const totalNutrition = {
          protein: 0,
          fat: 0,
          carbohydrate: 0
        };
        
        for (let j = 0; j < foodCount; j++) {
          const food = getRandomElement(foods);
          const amount = getRandomInt(50, 300); // 食用量50-300克/毫升
          
          // 计算实际摄入的营养成分
          const ratio = amount / 100; // 食物营养成分通常以100g为单位
          const calories = Math.round(food.calories * ratio);
          const protein = Math.round(food.nutrition.protein * ratio);
          const fat = Math.round(food.nutrition.fat * ratio);
          const carbohydrate = Math.round(food.nutrition.carbohydrate * ratio);
          
          totalCalories += calories;
          totalNutrition.protein += protein;
          totalNutrition.fat += fat;
          totalNutrition.carbohydrate += carbohydrate;
          
          mealFoods.push({
            food: {
              _id: food._id,
              name: food.name,
              image: food.image,
              unit: food.unit,
              calories: food.calories
            },
            amount,
            unit: food.unit,
            calories,
            nutrition: {
              protein,
              fat,
              carbohydrate
            }
          });
        }
        
        // 生成饮食记录
        const hours = mealType === '早餐' ? getRandomInt(6, 9) :
                      mealType === '午餐' ? getRandomInt(11, 14) :
                      mealType === '晚餐' ? getRandomInt(17, 20) :
                      getRandomInt(14, 17); // 加餐时间
        
        const minutes = getRandomInt(0, 59);
        const timeStr = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`;
        
        records.push({
          _id: createObjectId(),
          userId: user._id,
          mealType,
          date,
          time: timeStr,
          foods: mealFoods,
          totalCalories,
          totalNutrition,
          note: `${mealType}记录`,
          images: Math.random() > 0.7 ? [getUnsplashImage(600, 400, `${mealType},food,plate`)] : [], // 30%概率有图片
          createdAt: new Date(date.getFullYear(), date.getMonth(), date.getDate(), hours, minutes),
          updatedAt: new Date(date.getFullYear(), date.getMonth(), date.getDate(), hours, minutes)
        });
      }
    }
  });
  
  return records;
}

// 创建索引函数
async function createIndexes(db) {
  console.log('开始创建索引...');
  
  // 用户相关索引
  await db.collection('users').createIndex({ "openid": 1 }, { unique: true });
  await db.collection('users').createIndex({ "unionid": 1 });
  await db.collection('users').createIndex({ "nickname": 1 });
  await db.collection('users').createIndex({ "createdAt": -1 });

  await db.collection('admin_users').createIndex({ "username": 1 }, { unique: true });
  await db.collection('admin_users').createIndex({ "email": 1 }, { unique: true });
  await db.collection('admin_users').createIndex({ "role": 1 });
  
  // 食物相关索引
  await db.collection('foods').createIndex({ "name": 1 });
  await db.collection('foods').createIndex({ "category._id": 1 });
  await db.collection('foods').createIndex({ "calories": 1 });
  await db.collection('foods').createIndex({ "isVerified": 1 });

  await db.collection('food_favorites').createIndex({ "userId": 1, "foodId": 1 }, { unique: true });
  await db.collection('food_favorites').createIndex({ "createdAt": -1 });

  await db.collection('search_history').createIndex({ "userId": 1, "type": 1, "createdAt": -1 });
  await db.collection('search_history').createIndex({ "keyword": 1 });
  
  // 饮食记录相关索引
  await db.collection('diet_records').createIndex({ "userId": 1, "date": -1 });
  await db.collection('diet_records').createIndex({ "userId": 1, "mealType": 1, "date": -1 });
  
  // 食谱相关索引
  await db.collection('recipes').createIndex({ "title": 1 });
  await db.collection('recipes').createIndex({ "category._id": 1 });
  await db.collection('recipes').createIndex({ "tags": 1 });
  await db.collection('recipes').createIndex({ "author._id": 1 });
  await db.collection('recipes').createIndex({ "viewCount": -1 });
  await db.collection('recipes').createIndex({ "rating": -1 });

  await db.collection('recipe_favorites').createIndex({ "userId": 1, "recipeId": 1 }, { unique: true });
  
  // 营养相关索引
  await db.collection('nutrition_goals').createIndex({ "userId": 1 }, { unique: true });

  await db.collection('nutrition_suggestions').createIndex({ "userId": 1, "createdAt": -1 });
  await db.collection('nutrition_suggestions').createIndex({ "userId": 1, "isRead": 1 });
  
  // 系统管理相关索引
  await db.collection('system_configs').createIndex({ "key": 1 }, { unique: true });
  await db.collection('system_configs').createIndex({ "category": 1, "isActive": 1 });

  await db.collection('user_activity_logs').createIndex({ "userId": 1, "createdAt": -1 });
  await db.collection('user_activity_logs').createIndex({ "actionType": 1, "module": 1 });
  await db.collection('user_activity_logs').createIndex({ "createdAt": -1 });
  await db.collection('user_activity_logs').createIndex({ "status": 1 });

  await db.collection('statistics_cache').createIndex({ "cacheKey": 1 }, { unique: true });
  await db.collection('statistics_cache').createIndex({ "module": 1, "cacheType": 1 });
  await db.collection('statistics_cache').createIndex({ "expireAt": 1 }, { expireAfterSeconds: 0 });
  
  console.log('索引创建完成！');
}

// 创建索引函数修改为使用mongoose
async function createIndexes() {
  console.log('创建索引...');
  
  // 使用mongoose的模型创建索引
  const db = mongoose.connection;
  
  // 用户索引
  await db.collection('users').createIndex({ "openid": 1 }, { unique: true });
  await db.collection('users').createIndex({ "unionid": 1 });
  await db.collection('users').createIndex({ "nickname": 1 });
  await db.collection('users').createIndex({ "createdAt": -1 });
  await db.collection('users').createIndex({ "lastLoginAt": -1 });
  await db.collection('users').createIndex({ "isActive": 1 });

  // 管理员用户索引
  await db.collection('admin_users').createIndex({ "username": 1 }, { unique: true });
  await db.collection('admin_users').createIndex({ "email": 1 }, { unique: true });
  await db.collection('admin_users').createIndex({ "role": 1 });
  await db.collection('admin_users').createIndex({ "isActive": 1 });

  // 食物索引
  await db.collection('foods').createIndex({ "name": 1 });
  await db.collection('foods').createIndex({ "category._id": 1 });
  await db.collection('foods').createIndex({ "calories": 1 });
  await db.collection('foods').createIndex({ "isVerified": 1 });

  // 食物分类索引
  await db.collection('food_categories').createIndex({ "name": 1 }, { unique: true });
  await db.collection('food_categories').createIndex({ "order": 1 });
  await db.collection('food_categories').createIndex({ "isActive": 1 });

  // 食谱索引
  await db.collection('recipes').createIndex({ "title": 1 });
  await db.collection('recipes').createIndex({ "category._id": 1 });
  await db.collection('recipes').createIndex({ "tags": 1 });
  await db.collection('recipes').createIndex({ "author._id": 1 });
  await db.collection('recipes').createIndex({ "difficulty": 1 });
  await db.collection('recipes').createIndex({ "isVerified": 1 });
  await db.collection('recipes').createIndex({ "viewCount": -1 });
  await db.collection('recipes').createIndex({ "favoriteCount": -1 });
  await db.collection('recipes').createIndex({ "rating": -1 });
  await db.collection('recipes').createIndex({ "createdAt": -1 });

  // 食谱分类索引
  await db.collection('recipe_categories').createIndex({ "name": 1 }, { unique: true });
  await db.collection('recipe_categories').createIndex({ "order": 1 });
  await db.collection('recipe_categories').createIndex({ "isActive": 1 });

  // 食物收藏索引
  await db.collection('food_favorites').createIndex({ "userId": 1, "foodId": 1 }, { unique: true });
  await db.collection('food_favorites').createIndex({ "createdAt": -1 });

  // 食谱收藏索引
  await db.collection('recipe_favorites').createIndex({ "userId": 1, "recipeId": 1 }, { unique: true });
  await db.collection('recipe_favorites').createIndex({ "createdAt": -1 });

  // 搜索历史索引
  await db.collection('search_history').createIndex({ "userId": 1, "keyword": 1 });
  await db.collection('search_history').createIndex({ "userId": 1, "createdAt": -1 });
  await db.collection('search_history').createIndex({ "module": 1 });

  // 饮食记录索引
  await db.collection('diet_records').createIndex({ "userId": 1, "date": -1 });
  await db.collection('diet_records').createIndex({ "mealType": 1 });
  await db.collection('diet_records').createIndex({ "foods.foodId": 1 });

  // 营养目标索引
  await db.collection('nutrition_goals').createIndex({ "userId": 1 }, { unique: true });
  await db.collection('nutrition_goals').createIndex({ "updatedAt": -1 });

  // 营养建议索引
  await db.collection('nutrition_suggestions').createIndex({ "userId": 1, "date": -1 });
  await db.collection('nutrition_suggestions').createIndex({ "type": 1 });

  // 系统配置索引
  await db.collection('system_configs').createIndex({ "key": 1 }, { unique: true });
  await db.collection('system_configs').createIndex({ "category": 1, "isActive": 1 });

  // 用户活动日志索引
  await db.collection('user_activity_logs').createIndex({ "userId": 1, "createdAt": -1 });
  await db.collection('user_activity_logs').createIndex({ "actionType": 1, "module": 1 });
  await db.collection('user_activity_logs').createIndex({ "createdAt": -1 });
  await db.collection('user_activity_logs').createIndex({ "status": 1 });

  // 统计缓存索引
  await db.collection('statistics_cache').createIndex({ "cacheKey": 1 }, { unique: true });
  await db.collection('statistics_cache').createIndex({ "module": 1, "cacheType": 1 });
  await db.collection('statistics_cache').createIndex({ "expireAt": 1 }, { expireAfterSeconds: 0 });
  
  console.log('索引创建完成！');
}

// 主函数
async function main() {
  try {
    console.log('开始初始化数据库...');
    
    // 连接到MongoDB
    await mongoose.connect(uri, {
      useNewUrlParser: true,
      useUnifiedTopology: true
    });
    console.log('已连接到MongoDB');
    
    const db = mongoose.connection;
    
    // 清空现有数据
    console.log('清空现有数据...');
    const collections = [
      'users', 'admin_users', 'foods', 'food_categories', 'food_favorites',
      'search_history', 'diet_records', 'recipes', 'recipe_categories',
      'recipe_favorites', 'nutrition_goals', 'nutrition_suggestions',
      'system_configs', 'user_activity_logs', 'statistics_cache'
    ];
    
    // 确保所有集合都被清空
    try {
      for (const collection of collections) {
        if (await db.collection(collection).countDocuments() > 0) {
          await db.collection(collection).deleteMany({});
          console.log(`已清空集合: ${collection}`);
        }
      }
    } catch (err) {
      console.warn('清空数据时出现警告:', err.message);
    }
    
    // 删除所有索引（除了_id索引）
    try {
      for (const collection of collections) {
        await db.collection(collection).dropIndexes();
        console.log(`已删除集合 ${collection} 的索引`);
      }
    } catch (err) {
      console.warn('删除索引时出现警告:', err.message);
    }
    
    // 生成测试数据
    console.log('生成测试数据...');
    
    // 1. 生成管理员用户
    const adminUsers = await generateAdminUsers();
    await db.collection('admin_users').insertMany(adminUsers);
    console.log(`已创建 ${adminUsers.length} 个管理员用户`);
    
    // 2. 生成普通用户
    const users = await generateUsers(20);
    await db.collection('users').insertMany(users);
    console.log(`已创建 ${users.length} 个普通用户`);
    
    // 3. 生成食物分类
    const foodCategories = generateFoodCategories();
    await db.collection('food_categories').insertMany(foodCategories);
    console.log(`已创建 ${foodCategories.length} 个食物分类`);
    
    // 4. 生成食物数据
    const foods = generateFoods(foodCategories);
    await db.collection('foods').insertMany(foods);
    console.log(`已创建 ${foods.length} 个食物`);
    
    // 5. 生成食谱分类
    const recipeCategories = generateRecipeCategories();
    await db.collection('recipe_categories').insertMany(recipeCategories);
    console.log(`已创建 ${recipeCategories.length} 个食谱分类`);
    
    // 6. 生成食谱数据
    const recipes = generateRecipes(recipeCategories, foods, adminUsers[0]);
    await db.collection('recipes').insertMany(recipes);
    console.log(`已创建 ${recipes.length} 个食谱`);
    
    // 7. 生成系统配置
    const systemConfigs = generateSystemConfigs(adminUsers[0]);
    await db.collection('system_configs').insertMany(systemConfigs);
    console.log(`已创建 ${systemConfigs.length} 个系统配置`);
    
    // 8. 生成用户活动日志
    const userActivityLogs = generateUserActivityLogs(users, adminUsers[0]);
    await db.collection('user_activity_logs').insertMany(userActivityLogs);
    console.log(`已创建 ${userActivityLogs.length} 条用户活动日志`);
    
    // 9. 生成营养建议
    const nutritionSuggestions = generateNutritionSuggestions(users);
    await db.collection('nutrition_suggestions').insertMany(nutritionSuggestions);
    console.log(`已创建 ${nutritionSuggestions.length} 条营养建议`);
    
    // 10. 生成营养目标
    const nutritionGoals = generateNutritionGoals(users);
    await db.collection('nutrition_goals').insertMany(nutritionGoals);
    console.log(`已创建 ${nutritionGoals.length} 条营养目标`);
    
    // 11. 生成食物收藏
    const foodFavorites = generateFoodFavorites(users, foods);
    await db.collection('food_favorites').insertMany(foodFavorites);
    console.log(`已创建 ${foodFavorites.length} 条食物收藏`);
    
    // 12. 生成食谱收藏
    const recipeFavorites = generateRecipeFavorites(users, recipes);
    await db.collection('recipe_favorites').insertMany(recipeFavorites);
    console.log(`已创建 ${recipeFavorites.length} 条食谱收藏`);
    
    // 13. 生成搜索历史
    const searchHistory = generateSearchHistory(users);
    await db.collection('search_history').insertMany(searchHistory);
    console.log(`已创建 ${searchHistory.length} 条搜索历史`);
    
    // 14. 生成饮食记录
    const dietRecords = generateDietRecords(users, foods);
    await db.collection('diet_records').insertMany(dietRecords);
    console.log(`已创建 ${dietRecords.length} 条饮食记录`);
    
    // 创建索引
    await createIndexes();
    
    console.log('数据库初始化完成！');
  } catch (err) {
    console.error('初始化数据库时出错:', err);
  } finally {
    await mongoose.disconnect();
    console.log('已关闭MongoDB连接');
  }
}

// 执行主函数
main().catch(console.error);